/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dto.Post;
import java.sql.*;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import util.DBUtil;

/**
 *
 * @author NHAN
 */
public class PostDAO {

    Connection conn;
    private int totalRecords = 0;
    String sqlSelectByID = "select * from Post where id=?";
    String sqlCreate = "insert into Post(title,content,category_id,class_id ,created_by,modified_date,state) values(?,?, ?, ?, ?,?,?)";
    String sqlUpdate = "update Post set title=?, content=?,category_id=?, created_by=?,modified_date=?,state=? where id=?";
    String sqlDelete = "delete from Post where id=?";
    Logger logger = Logger.getLogger(PostDAO.class);

    public PostDAO() {
    }

    /**
     * get a post by specifying identifier value
     *
     * @param id
     * @return Post object
     */
    public Post getPost(int id) {
        Post p = new Post();
        try {
            conn = DBUtil.getConnection();

            if (conn == null) {
                logger.info("Cannot get connection");
                return null;
            }//content,category_id,class_id ,created_by,modified_date,state
            PreparedStatement ps = conn.prepareStatement(sqlSelectByID);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                p.setTitle(rs.getString("title"));
                p.setContent(rs.getString("content"));
                p.getCategory().setId(rs.getInt("id"));
                p.getCls().setId(rs.getInt("class_id"));
                p.getAuthor().setFirstName(rs.getString("created_by"));
                p.setModifiedDate(rs.getDate("modified_date"));
                p.setState(rs.getBoolean("state"));
                p.setIsRead(rs.getBoolean("is_read"));
                p.setIsReplied(rs.getBoolean("is_replied"));
            }
            DBUtil.disconnect();

        } catch (SQLException ex) {
            logger.info("SQL error: " + ex.getMessage());
        } catch (Exception ex) {
            logger.info("Error: " + ex.getMessage());
        }
        return p;
    }

    /**
     *
     * @param currentPage current page to select
     * @param pageSize number of records per page
     * @return list of posts
     */
    public ArrayList<Post> getPosts(int currentPage, int pageSize) {
        ArrayList<Post> list = new ArrayList<Post>();
        try {
            conn = DBUtil.getConnection();
            if (conn == null) {
                logger.info("Cannot get connection");
                return null;
            }//content,category_id,class_id ,created_by,modified_date,state
            QueryObject qo = new QueryObject("Post", "id", "id");
            qo.setColumns("id, content,category_id,class_id ,created_by,modified_date,state");
            qo.setCurrentPage(currentPage);
            qo.setPageSize(pageSize);

            CallableStatement cs = qo.getCallableStatement(conn);
            ResultSet rs = cs.executeQuery();
            while (rs.next()) {
                Post p = new Post();
                p.setId(rs.getInt(1));
                p.setContent(rs.getString(2));
                p.getCategory().setId(rs.getInt(3));
                p.getCls().setId(rs.getInt(4));
                p.getAuthor().setFirstName(rs.getString(5));
                p.setModifiedDate(rs.getDate(6));
                p.setState(rs.getBoolean(7));
                list.add(p);
            }
            totalRecords = qo.getTotals();
        } catch (SQLException ex) {
            logger.info(ex.getMessage());
        } catch (Exception ex) {
            logger.info(ex.getMessage());
        }
        return list;
    }

    /**
     * add new post
     *
     * @param p post
     * @return greater than 0 value if the action is success, else return 0
     */
    public int create(Post p) {
        int effectedRows = 0;
        try {
            conn = DBUtil.getConnection();
            if (conn == null) {
                logger.info("Cannot get connection");
                return 0;
            }//content,category_id,class_id ,created_by,modified_date,state
            PreparedStatement ps = conn.prepareStatement(sqlCreate);
            ps.setString(1, p.getTitle());
            ps.setString(2, p.getContent());
            ps.setInt(3, p.getCategory().getId());
            ps.setInt(4, p.getCls().getId());
            ps.setInt(5, p.getAuthor().getId());
            ps.setDate(6, new java.sql.Date(p.getModifiedDate().getTime()));
            ps.setBoolean(7, p.isState());          
            effectedRows = ps.executeUpdate();
            DBUtil.disconnect();
        } catch (SQLException ex) {
            logger.info(ex.getMessage());
        } catch (Exception ex) {
            logger.info(ex.getMessage());
        }
        return effectedRows;
    }

    /**
     * update specified post
     *
     * @param p post to update
     * @return 1 or greater if action is successful, else return 0
     */
    public int update(Post p) {
        int effectedRows = 0;
        try {
            conn = DBUtil.getConnection();
            if (conn == null) {
                logger.info("Cannot get connection");
                return 0;
            }
            PreparedStatement ps = conn.prepareStatement(sqlUpdate);
            ps.setString(1, p.getTitle());
            ps.setString(2, p.getContent());
            ps.setInt(3, p.getCategory().getId());            
            ps.setInt(4, p.getAuthor().getId());
            ps.setDate(5, new java.sql.Date(p.getModifiedDate().getTime()));
            ps.setBoolean(6, p.isState());
            ps.setInt(7, p.getId());
            effectedRows = ps.executeUpdate();
            DBUtil.disconnect();
        } catch (SQLException ex) {
            logger.info(ex.getMessage());
        } catch (Exception ex) {
            logger.info(ex.getMessage());
        }
        return effectedRows;
    }

    /**
     * delete a post by specifying identifier value
     *
     * @param id
     * @return 1 or greater value if action is successful , else return 0
     */
    public int delete(int id) {
        int effectedRows = 0;
        try {
            conn = DBUtil.getConnection();
            if (conn == null) {
                logger.info("Cannot get connection");
                return 0;
            }
            PreparedStatement ps = conn.prepareStatement(sqlDelete);
            ps.setInt(1, id);
            effectedRows = ps.executeUpdate();
            DBUtil.disconnect();
        } catch (SQLException ex) {
            logger.info(ex.getMessage());
        } catch (Exception ex) {
            logger.info(ex.getMessage());
        }
        return effectedRows;
    }

    /**
     * @return the totalRecords
     */
    public int getTotalRecords() {
        return totalRecords;
    }

    /**
     * @param totalRecords the totalRecords to set
     */
    public void setTotalRecords(int totalRecords) {
        this.totalRecords = totalRecords;
    }
}
